package cn.itcast.bos.web.action.system;

import cn.itcast.bos.domain.system.User;
import cn.itcast.bos.pagehelper.PageResult;
import cn.itcast.bos.result.Result;
import cn.itcast.bos.service.system.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/userListAndCondition.action")
    @ResponseBody
    public PageResult userListAndCondition(int page,int rows){
        return userService.userListAndCondition(page,rows);
    }

    @RequestMapping("/saveUser.action")
    @ResponseBody
    public Result saveUser(User user,String[] roleIds,String salary){
        if(user != null && user.getId() != null){
            Result result = new Result(true, "修改成功!");
            try {
                user.setRemark(salary);
                userService.updateUser(user, roleIds);
            } catch (Exception e) {
                result = new Result(false, "修改失败!");
                e.printStackTrace();
            }
            return result;
        }else {
            Result result = new Result(true, "保存成功!");
            try {
                user.setRemark(salary);//工资
                userService.saveUser(user, roleIds);
            } catch (Exception e) {
                result = new Result(false, "保存失败!");
                e.printStackTrace();
            }
            return result;
        }

    }

    @RequestMapping("/selectUserById.action")
    @ResponseBody
    public List<Map<String,Object>> selectUserById(Integer id){
        List<Map<String,Object>> userMap = userService.selectUserById(id);
        return userMap;
    }


    /**
     * 用户登录:
     */
    @RequestMapping("/userLogin.action")
    public String userLogin(String username,String password){

        // 用户名和密码 都保存在model中
        // 基于shiro实现登录
        Subject subject = SecurityUtils.getSubject();

        // 用户名和密码信息
        AuthenticationToken token = new UsernamePasswordToken(username,password);

        try {
            subject.login(token);
            return "redirect:/index.html";
        }catch(AuthenticationException e){
            e.printStackTrace();
            return "redirect:/login.html";
        }
    }
    @RequestMapping("user_logout")
    public String logout() {
        // 基于shiro完成退出
        Subject subject = SecurityUtils.getSubject();
        subject.logout();

        return "redirect:/login.html";
    }
}
